package com.haojin.exer;

import org.junit.Test;

/**
 * @author .29.
 * @create 2022-04-03 18:38
 */
public class StringDemo {
    /*
    将一个字符串进行反转，将字符串中指定部分进行反转，比如：abcdefg --> abfedcg
     */

    //方式一：转换为char
    public String reverse(String str,int startIndex,int endIndex){
        if(str != null){
            char[] charArray = str.toCharArray();
            for(int i =startIndex,j = endIndex;i<j; i++,j--){
                char temp = charArray[i];
                charArray[i] = charArray[j];
                charArray[j] = temp;
            }
            return new String(charArray);
        }else return null;
    }
    //方式二：使用String的拼接
    public String reverse1(String str,int startIndex,int endIndex){
        if(str != null){
            String reverseStr = str.substring(0,startIndex);
            for(int i = endIndex;i>=startIndex;i--){
                reverseStr += str.charAt(i);
            }
            reverseStr += str.substring(endIndex+1);
            return reverseStr;
        }else return null;
    }
    //方式三：使用StringBuffer或StringBuilder替换String
    public String reverse2(String str,int startIndex,int endIndex){
        if(str != null){
            StringBuilder builder = new StringBuilder(str.length());
            builder.append(str.substring(0,startIndex));
            for(int i = endIndex;i>=startIndex;i--){
                builder.append(str.charAt(i));
            }
            builder.append(str.substring(endIndex+1));
            return builder.toString();
        }else return null;
    }


    @Test
    public void reverse(){
        String str = new String("abcdefg");
        String str1 = reverse(str,2,5);
        String str2 = reverse1(str,2,5);
        String str3 = reverse2(str,2,5);
        System.out.println(str);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }
}
